import {createRouter, createWebHistory, RouteRecordRaw} from 'vue-router'
import {ElMessage} from "element-plus";

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'model',
    component: () => import(/* webpackChunkName: "model" */ '../views/model/modelList.vue')
  }, {
    path: '/myModel',
    name: 'myModel',
    meta: {requiresAuth: true},
    component: () => import(/* webpackChunkName: "myModel" */ '../views/model/myModel.vue')
  }, {
    path: '/package',
    name: 'package',
    component: () => import(/* webpackChunkName: "package" */ '../views/vipPage.vue')
  }, {
    path: '/order',
    name: 'order',
    meta: {requiresAuth: true},
    component: () => import(/* webpackChunkName: "order" */ '../views/order/orderPage.vue')
  }, {
    path: '/user',
    name: 'user',
    meta: {requiresAuth: true},
    component: () => import(/* webpackChunkName: "user" */ '../views/user/userPage.vue')
  }, {
    path: '/myVip',
    name: 'myVip',
    component: () => import(/* webpackChunkName: "myVip" */ '../views/user/userVip.vue')
  }, {
    path: '/cart',
    name: 'cart',
    meta: {requiresAuth: true},
    component: () => import(/* webpackChunkName: "cart" */ '../views/order/cartPage.vue')
  }, {
    path: '/wallet',
    name: 'wallet',
    meta: {requiresAuth: true},
    component: () => import(/* webpackChunkName: "wallet" */ '../views/finance/walletPage.vue')
  }, {
    path: '/invoice',
    name: 'invoice',
    component: () => import(/* webpackChunkName: "invoice" */ '../views/finance/invoicePage.vue')
  }, {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login.vue')
  }, {
    path: '/create',
    name: 'create',
    meta: {requiresAuth: true},
    component: () => import(/* webpackChunkName: "create" */ '../views/order/createPage.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach(async (to, from, next) => {

  const isLoggedIn = checkUserLoginStatus()
  if (to.meta.requiresAuth && !isLoggedIn) {
    next({ name: 'model' }) // 记录来源路径
    ElMessage.warning("请登录后操作")
    return
  }

  // if (to.meta.requiresGuest && isLoggedIn) {
  //   next({ name: 'model' })
  //   return
  // }
  next()
})


function checkUserLoginStatus() {
  return !!localStorage.getItem('access_token')
}

export default router
